#include "subthread1.h"

SubThread1::SubThread1(QObject *parent)
    : QObject{parent}
{
    tableName = QDate::currentDate().toString("yyyy-MM-dd");
}

void SubThread1::SubThread1_Run(QTime time,qreal vms,qreal tms)
{
    struct MeasureData md;
    md.Time = time;
    md.Vms = vms;
    md.Tms = tms;
    measureDataQueue.enqueue(md);
    mutex.lock();
    if(measureDataQueue.size() > 60){
        //开始写入数据库
        //打开数据库
        {
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE","SubThreadConnect");
            db.setDatabaseName("./tssDB.db");
            db.setPassword("4414");
            if(!db.open()){
                qDebug() << "Fail to open DB";
              return;
            }else{
                qDebug() << "succeed to open DB";
            }
            QSqlQuery query(db);
            query.prepare(QString("insert into \"%1\"(Time, Vms, Tms) values(:Time, :Vms, :Tms);").arg(tableName));
            QVariantList TimeList,VmsList,TmsList;
            //循环取出数值
            while(!measureDataQueue.isEmpty()){
                md = measureDataQueue.dequeue();
                //QString();
                TimeList << md.Time.toString("hh:mm:ss");
                VmsList  << md.Vms;
                TmsList  << md.Tms;
            }
            //数值写入
            query.bindValue(":Time",TimeList);
            query.bindValue(":Vms",VmsList);
            query.bindValue(":Tms",TmsList);
            //执行预处理命令
            query.execBatch();
            //关闭数据库
            db.close();
        }
        QSqlDatabase::removeDatabase("SubThreadConnect");
    }
    mutex.unlock();
    /*
    mutex.lock();
    mutex.unlock();
    */
}


